import { defineStore } from 'pinia';
import {
    getAllUsers,
    getUserByUserId,
    getUserByUsername,
    getUserByUserPhone,
    deleteUserById,
    updateUser
} from '../api/user.js';

export const useUserStore = defineStore('user', {
    state: () => ({
        users: [],
        loading: false,
        error: null,
        selectedUser: {
            userid: '',
            username: '',
            userphone: ''
        },
        updateKey: 0 // 强制更新标识
    }),
    actions: {
        async fetchUsers() {
            this.loading = true;
            this.error = null;
            try {
                const response = await getAllUsers();
                if (response.data.code === 1) {
                    this.users = response.data.data;
                    console.log('fetchUsers users:', this.users);
                    this.updateKey++; // 增加更新标识
                    console.log('fetchUsers updateKey:', this.updateKey); // 打印updateKey
                } else {
                    this.error = response.data.msg || '获取用户列表失败';
                }
            } catch (error) {
                this.error = '网络请求失败';
                console.error(error);
            } finally {
                this.loading = false;
            }
        },

        async fetchUserByUserId(userid) {
            this.loading = true;
            this.error = null;
            try {
                const response = await getUserByUserId(userid);
                if (response.data.code === 1) {
                    this.users = response.data.data;
                    this.updateKey++; // 关键点：触发表格重新渲染
                } else {
                    this.error = response.data.msg || '用户不存在';
                    this.users = [];
                    this.updateKey++; // 即使无数据也更新
                }
            } catch (error) {
                this.error = '网络请求失败';
                this.users = [];
                this.updateKey++; // 失败时也更新
                console.error(error);
            } finally {
                this.loading = false;
            }
        },

        async fetchUserByUsername(username) {
            this.loading = true;
            this.error = null;
            try {
                const response = await getUserByUsername(username);
                if (response.data.code === 1) {
                    this.users = response.data.data;
                    this.updateKey++; // 关键点
                } else {
                    this.error = response.data.msg || '用户不存在';
                    this.users = [];
                    this.updateKey++;
                }
            } catch (error) {
                this.error = '网络请求失败';
                this.users = [];
                this.updateKey++;
                console.error(error);
            } finally {
                this.loading = false;
            }
        },

        async fetchUserByUserPhone(userphone) {
            this.loading = true;
            this.error = null;
            try {
                const response = await getUserByUserPhone(userphone);
                if (response.data.code === 1) {
                    this.users = response.data.data;
                    this.updateKey++; // 关键点
                } else {
                    this.error = response.data.msg || '用户不存在';
                    this.users = [];
                    this.updateKey++;
                }
            } catch (error) {
                this.error = '网络请求失败';
                this.users = [];
                this.updateKey++;
                console.error(error);
            } finally {
                this.loading = false;
            }
        },

        async deleteUser(userid) {
            this.loading = true;
            this.error = null;
            try {
                const response = await deleteUserById(userid);
                if (response.data.code === 1) {
                    this.users = this.users.filter(user => user.userid !== userid);
                    this.updateKey++; // 关键点
                } else {
                    this.error = response.data.msg || '删除失败';
                    throw new Error(this.error);
                }
            } catch (error) {
                this.error = error.message || '网络请求失败';
                throw error;
            } finally {
                this.loading = false;
            }
        },

        async updateUser(user) {
            this.loading = true;
            this.error = null;
            try {
                const response = await updateUser(user);
                if (response.data.code === 1) {
                    const index = this.users.findIndex(u => u.userid === user.userid);
                    if (index !== -1) {
                        this.users = this.users.map(u =>
                            u.userid === user.userid ? { ...u, ...user } : u
                        );
                        this.updateKey++; // 关键点
                    }
                } else {
                    this.error = response.data.msg || '更新失败';
                    throw new Error(this.error);
                }
            } catch (error) {
                this.error = error.message || '网络请求失败';
                throw error;
            } finally {
                this.loading = false;
            }
        }
    }
});